﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;

namespace WinPhoneEnergyMonitor
{
    public partial class MainPage : PhoneApplicationPage
    {
        string baseUri = "http://bookle.dnsalias.com:8888/EnergyMonWs.svc";

        public MainPage()
        {
            InitializeComponent();

            SupportedOrientations = SupportedPageOrientation.Portrait;
            Timer tmr = new Timer(UpdateScreen, null, 0, 15000);
        }

        private void UpdateScreen(object state)
        {
            UpdateValueFromWebService("energy", this.energyValue);
            UpdateValueFromWebService("temp", this.tempValue);
            UpdateValueFromWebService("time", this.timeValue);
            UpdateValueFromWebService("date", this.dateValue);
        }

        private string UpdateValueFromWebService(string reading, TextBlock tb)
        {
            string retVal = "N/A";
            Uri uri = new Uri(baseUri + "/json/" + reading);

            try
            {
                WebClient wc = new WebClient();
                wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted);
                wc.DownloadStringAsync(uri, tb);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error (UpdateValueFromWebService) : " + ex.Message);
            }

            return retVal;
        }

        void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string val = e.Result.Replace("\"", "").Replace("\\", "");
                System.Diagnostics.Debug.WriteLine(val);
                ((TextBlock)e.UserState).Text = val;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error (DownloadStringCompleted) : " + ex.Message);
            }
        }

    }
}